<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Block_Post_Filter_Category extends Block_Post_Filter_Abstract {

	protected $_from = 'cat_index';
	
	protected $_items = null;
	
	public function __construct() {
		$this->_requestVar = 'cat';
		$this->setTemplate('post/filter/category');
		$cache = App::objectSingleton('Entity_Category_Cache');
		if (!$cache->isValid()) $cache->refresh();
	}
	
	public function apply() {
		if (App::get($this->getRequestVar())) {
			// get applied values
			$catId = App::get($this->_requestVar);
			$this->_appliedValues = array($catId);
			
			// append filter to collection
			$select = $this->getLayer()->getCollection()->getSelect();
			$select->join($this->_from, "post.category = cat_index.descendant AND cat_index.ancestor = $catId AND cat_index.ancestor = cat_index.descendant");
			//$select->join($this->_from, "post.category = cat_index.descendant AND cat_index.ancestor = $catId");
		}
	}
	
	protected function _beforeRender() {
		$this->_prepareChilds($this, null);	// create top level blocks
	}

	protected function _prepareChilds($parentBlock, $parent) {
		$items = $this->getItems($parent);
		foreach ($items as $item) {
			// create & append block to parent
			$block = $this->getLayout()->createBlock($parentBlock->getName().'_'.$item['value']);
			$block->setItem($item)->setTemplate('post/filter/category/item');
			$parentBlock->append($block);

			// create childs block recursively
            $this->_prepareChilds($block, $item['value']);
		}
	}
	
	public function getItems($parent) {
		if ($this->_items == null) {
			$select = clone $this->getLayer()->getCollection()->getSelect();
			$from = $select->getPart(Core_Db_Select::FROM);
			unset($from[$this->_from]);
			$select->setPart(Core_Db_Select::FROM, $from);

			$select->setPart(Core_Db_Select::COLUMNS, array('post.id'))
				->resetPart(Core_Db_Select::LIMIT)
				->resetPart(Core_Db_Select::ORDER);

			// include sub category
			$select = 'SELECT cat.*, COUNT(p.id) as post_count '
				.'FROM category cat '
				.'JOIN cat_index idx ON cat.id = idx.ancestor AND idx.ancestor = idx.descendant '
				//.'JOIN cat_index idx ON cat.id = idx.ancestor '
				."LEFT JOIN post p ON p.category = idx.descendant AND p.id IN ($select) "
				.'GROUP BY cat.id ORDER BY sort_order ASC';
			$rows = App::db()->query($select)->result_array();

			$this->_items = array();
			foreach($rows as $row) {
				array_push($this->_items, array(
					'label' => $row['name'],
					'value' => $row['id'],
					'count' => $row['post_count'],
					'selected' => in_array($row['id'], $this->getAppliedValues()),
					'url' => $this->getItemUrl($row['id']),
					'parent' => $row['parent_category']
				));
			}
		}
		
		$res = array();
		foreach($this->_items as $item)
			if ($item['parent'] == $parent)
				array_push($res, $item);
		return $res;
	}
}